// yb_shop/pages/poster/index.js
var app = getApp();
let wechat = require("../..//utils/wechat.js");
var core = require("../..//utils/core.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    src:'',
    paths:{
      goods:'yb_shop/pages/goods/detail/index',
      kanjia: 'yb_shop/pages/kanjia/goods_info/index',
      pintuan: 'yb_shop/pages/pintuan/pages/goods/detail',
    }
  },

  dosave: function()
  {
    if (this.data.src.length > 0)
    {
      wx.showLoading({title:'保存中...'});
      wechat.saveImageToPhotosAlbum(this.data.src).then(d => {
        wx.hideLoading();
        core.alert("海报保存成功");
      }).catch(e => {
        wx.hideLoading();
        core.alert("海报保存失败,请重试");
      })
    }
    else
    {
      core.alert("海报正在生成,请稍候");
    }
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    console.log(options);
    var path = this.data.paths[options.share_type];
    var id = options.id;
   
    var pic_url = app.util.makeurl({
      url: 'entry/wxapp/net_img', data: {
        url: encodeURIComponent(options.img)
      }
    });

    options.img = pic_url;

    console.log(pic_url);
core.loading('海报生成中');
    const ctx = wx.createCanvasContext('poster');
    ctx.clearRect(0, 0, 0, 0); 

    ctx.setFillStyle('#ffffff')
    ctx.fillRect(0, 0, 750, 1030)

    const CONTENT_ROW_LENGTH = 34;  // 正文 单行显示字符长度
    let [contentLeng, contentArray, contentRows] = this.textByteLength(options.title, CONTENT_ROW_LENGTH);
    ctx.setTextAlign('left')
    ctx.setFontSize(28);
    ctx.setFillStyle("#333333");
    let contentHh = 35;
    for (let m = 0; m < contentArray.length; m++) {
      ctx.fillText(contentArray[m], 12, 805 + contentHh * m);
    }
    var price = "原价￥" + (options.original_price);
    ctx.setFontSize(22);
    ctx.setFillStyle("#818181");
    ctx.fillText(price, 12, 920);
    const metrics = ctx.measureText(price);

    ctx.setFontSize(22);
    ctx.setFillStyle("#333333");
    ctx.fillText("优惠价￥", 12, 990);

    ctx.setFontSize(48);
    ctx.setFillStyle("#d92d20");
    ctx.fillText(options.price, 100, 993);

    // ctx.setFontSize(22);
    // ctx.setFillStyle("#fc8d42");
    // ctx.fillText("长按识别", 530, 995);
    
    ctx.setStrokeStyle("#818181")
    ctx.beginPath()
    ctx.setLineWidth(1)
    ctx.moveTo(12, 911)
    ctx.lineTo(metrics.width + 12, 911)
    ctx.stroke()

    var url = app.util.makeurl({url:'entry/wxapp/qr_code',data:{
      path: path,
      scene: id,
      pid:app.getCache('userinfo').uid
    }});

    console.log(url);

    var md5 = app.util.md5("share_type=" + options.share_type + "&id=" + options.id);
    var qrcode_path = app.getCache(md5);
    console.log(qrcode_path);
    
    var that = this;
    if (qrcode_path != "")
    {
      console.log("has save !!!!!!!");
      ctx.drawImage(qrcode_path, 490, 765, 236, 236);
      wechat.downloadFile(options.img)
        .then(d => {
          console.log(d);
          ctx.drawImage(d.tempFilePath, 0, 0, 750, 750);
          
          ctx.draw(false, function () {
            wx.canvasToTempFilePath({
              destWidth: 750,
              destHeight: 1030,
              canvasId: 'poster',
              success: function (res) {
                core.hideLoading();
                console.log(res.tempFilePath)
                that.setData({
                  src: res.tempFilePath
                });
              }
            })
          });
      })
      .catch(err => {
        core.alert("商品图片无法下载,海报生成失败");
      })
    }
    else
    {
      console.log("not save !!!!!!!");

      wechat.downloadFile(options.img)
      .then(d => {
          console.log(d);
        ctx.drawImage(d.tempFilePath, 0, 0, 750, 750);
        return wechat.downloadFile(url);
      })
      .then(d => {
        console.log(d);
        return wechat.saveFile(d.tempFilePath);
      })
      .then(d => {
        console.log(d);
        var savedFilePath = d.savedFilePath;
        app.setCache(md5, savedFilePath);
        ctx.drawImage(savedFilePath, 490, 765, 236, 236);
        ctx.draw(false,function(){
          wx.canvasToTempFilePath({
            destWidth: 750,
            destHeight: 1030,
            canvasId: 'poster',
            success: function (res) {
              console.log(res)
              core.hideLoading();
              that.setData({
                src: res.tempFilePath
              });
            }
            })
          });

      })
      .catch(err => {
        core.alert("商品图片无法下载,海报生成失败");
      })
     }
    
  },

  textByteLength: function(text, num) {  // text为传入的文本  num为单行显示的字节长度
    let strLength = 0; // text byte length
    let rows = 1;
    let str = 0;
    let arr = [];
    for (let j = 0; j < text.length; j++) {
      if (text.charCodeAt(j) > 255) {
        strLength += 2;
        if (strLength > rows * num) {
          strLength++;
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      } else {
        strLength++;
        if (strLength > rows * num) {
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      }
    }
    arr.push(text.slice(str, text.length));
    return [strLength, arr, rows]   //  [处理文字的总字节长度，每行显示内容的数组，行数]
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})